package main

import (
	"fmt"
	"os"
	"time"
)

var log = "sdjsldlsjdlsjdlsajdlsalsdldsds\n"

func WriteDirect(outFile string) {
	fout, err := os.OpenFile(outFile, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		panic(err)
	}
	defer fout.Close()
	for i := 0; i < 10000; i++ {
		fout.WriteString(log)
	}
}

type BufferFileWirte struct {
	fout          *os.File
	cache         []byte
	cacheEndIndex int
}

func NewBufferdFileWriter(fout *os.File, cacheSize int) *BufferFileWirte {
	return &BufferFileWirte{fout: fout, cache: make([]byte, cacheSize), cacheEndIndex: 0}
}
func (w *BufferFileWirte) WriteBytes(cont []byte) {
	if len(cont) >= len(w.cache) {
		w.Flush()
		w.fout.Write(cont)
	} else {
		if len(cont)+w.cacheEndIndex >= len(w.cache) {
			w.Flush()
		}
		copy(w.cache[w.cacheEndIndex:], cont)
		w.cacheEndIndex += len(cont)
	}
}
func (w *BufferFileWirte) Flush() {
	w.fout.Write(w.cache[0:w.cacheEndIndex])
	w.cacheEndIndex = 0
}

func main() {
	t := time.Now()
	WriteDirect("a.txt")
	fmt.Printf(" %dms \n", time.Since(t).Microseconds())
}
